﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using Brettle.Web.NeatUpload;
using Aspose.Slides;
//using Aspose.Slides;

namespace HealthCommunity.Controls
{
	public partial class UCMaterialEdit : System.Web.UI.UserControl
	{
		private IMaterialProvider _MaterialProvider;
		private List<DrugStore> lstDrugStore;

		private Material _CurrentMaterial;

		public int MaterialID
		{
			get
			{
				var id = 0;

				if(ViewState["MaterialID"] != null)
				{
					id = (int)ViewState["MaterialID"];
				}
				else
				{
					id = CommonHelper.QueryStringInt("materialid");
				}

				return id;
			}
			set
			{
				ViewState["MaterialID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindMaterialCategory();
				BindDrugStore();

				btnSave.Visible = (SiteContext.Current.CurrentUser != null);
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindMaterial();
		}

		protected void ddlDrugStore_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindMember();
		}

		protected void btnRemove_Click(object sender, EventArgs e)
		{
			if(lstMemberSelected.SelectedItem != null)
			{
				lstMemberSelected.Items.Remove(lstMemberSelected.SelectedItem);
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			if(lstMember.SelectedItem != null)
			{
				var item = new System.Web.UI.WebControls.ListItem(lstMember.SelectedItem.Text, lstMember.SelectedItem.Value);

				if(!lstMemberSelected.Items.Contains(item))
				{
					lstMemberSelected.Items.Add(item);
				}
			}
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			var user = SiteContext.Current.CurrentUser;
			if(user != null)
			{
				if(_MaterialProvider == null)
				{
					_MaterialProvider = new MaterialProvider();
				}

				var theMaterial = _MaterialProvider.GetMaterial(MaterialID);

				if(theMaterial == null)
				{
					theMaterial = new Material();
				}

				theMaterial.MaterialDescription = txtMaterialDescription.Text.Trim();
				theMaterial.MaterialName = txtMaterialName.Text.Trim();
				theMaterial.UploadUserID = user.UserID;

				var score = 0;
				int.TryParse(txtMaterialReqiredScore.Text.Trim(), out score);
				theMaterial.DownloadRequiedScore = score;

				var selectedMC = ddlMaterialCategory.SelectedValue;
				if(!string.IsNullOrEmpty(selectedMC))
				{
					theMaterial.MaterialCategoryID = int.Parse(selectedMC);
				}
				if(fuMaterialPath.HasFile)
				{
					//var url = Request.Url.Host;
					//if(Request.Url.Port > 0)
					//{
					//  url += ":" + Request.Url.Port.ToString();
					//}
					var path = Server.MapPath("~/Document");
					var fileNamePart = fuMaterialPath.FileName.Split('.');
					var fileExt = fileNamePart[fileNamePart.Length - 1];

					if(fileExt.Equals("pdf"))
					{
						var fileName = string.Format("{0}\\{1}.{2}", path, Guid.NewGuid().ToString(), fileExt);
						fuMaterialPath.MoveTo(fileName, MoveToOptions.Overwrite);
						theMaterial.MaterialSize = fuMaterialPath.FileContent.Length;
						theMaterial.MaterialPath = fileName;
					}
					else if(fileExt.Equals("doc") || fileExt.Equals("docx"))
					{
						var fileName = Guid.NewGuid().ToString() + ".pdf";
						var filePath = string.Format("{0}\\{1}", path, fileName);
						var tempFilePath = path + "\\UploadTemp\\";
						fuMaterialPath.MoveTo(tempFilePath + "\\" + fileName, MoveToOptions.Overwrite);
						Aspose.Words.Document d = new Aspose.Words.Document(tempFilePath + "\\" + fileName);
						d.Save(filePath);
						theMaterial.MaterialSize = fuMaterialPath.FileContent.Length;
						theMaterial.MaterialPath = filePath;
						//System.IO.File.Delete(tempFilePath + "\\" + fileName);
					}
					else if(fileExt.Equals("ppt"))
					{
						var fileName = Guid.NewGuid().ToString() + ".pdf";
						var filePath = string.Format("{0}\\{1}", path, fileName);
						var tempFilePath = path + "\\UploadTemp\\";
						fuMaterialPath.MoveTo(tempFilePath + "\\" + fileName, MoveToOptions.Overwrite);
						Presentation ppt = new Presentation(tempFilePath + "\\" + fileName);
						ppt.Save(filePath, Aspose.Slides.Export.SaveFormat.Pdf);
						theMaterial.MaterialSize = fuMaterialPath.FileContent.Length;
						theMaterial.MaterialPath = filePath;
						//System.IO.File.Delete(tempFilePath + "\\" + fileName);
					}
					else if(fileExt.Equals("pptx"))
					{
						var fileName = Guid.NewGuid().ToString() + ".pdf";
						var filePath = string.Format("{0}\\{1}", path, fileName);
						var tempFilePath = path + "\\UploadTemp\\";
						fuMaterialPath.MoveTo(tempFilePath + "\\" + fileName, MoveToOptions.Overwrite);
						Aspose.Slides.Pptx.PresentationEx ppt = new Aspose.Slides.Pptx.PresentationEx(fuMaterialPath.FileContent);
						ppt.Save(filePath, Aspose.Slides.Export.SaveFormat.Pdf);
						theMaterial.MaterialSize = fuMaterialPath.FileContent.Length;
						theMaterial.MaterialPath = filePath;
						//System.IO.File.Delete(tempFilePath + "\\" + fileName);
					}
				}

				theMaterial.IsPublic = chbIsPublic.Checked ? 1 : 0;

				if(this.MaterialID <= 0)
				{
					var msg = string.Empty;
					theMaterial.DrugStoreID = user.DrugStoreID;
					theMaterial.MaterialAddTime = DateTime.Now;
					theMaterial = _MaterialProvider.CreateMaterial(theMaterial, out msg);

					if(theMaterial != null && theMaterial.MaterialID > 0)
					{
						if(!chbIsPublic.Checked)
						{
							List<int> lstSelectedDrugStoreIDs = new List<int>();
							foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
							{
								if(item.Selected)
								{
									lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
								}
							}

							List<RLT_MaterialAndShareTo> lstNewMaterialAndShareTo = new List<RLT_MaterialAndShareTo>();

							if(lstSelectedDrugStoreIDs.Count > 0)
							{
								foreach(var id in lstSelectedDrugStoreIDs)
								{
									var rltMaterialAndShareTo = new RLT_MaterialAndShareTo() { MaterialID = theMaterial.MaterialID, ShareToDrugStoreID = id };
									lstNewMaterialAndShareTo.Add(rltMaterialAndShareTo);
								}
							}

							if(lstMemberSelected.Items.Count > 0)
							{
								foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
								{
									var memberID = int.Parse(item.Value);
									var rltMaterialAndShareTo = new RLT_MaterialAndShareTo() { MaterialID = theMaterial.MaterialID, ShareToMemberID = memberID };
									lstNewMaterialAndShareTo.Add(rltMaterialAndShareTo);
								}
							}

							if(lstNewMaterialAndShareTo.Count > 0)
							{
								_MaterialProvider.CreateMaterialAndShareTo(lstNewMaterialAndShareTo);
							}
						}

						ltrMsg.Text = "保存成功";
						this.MaterialID = theMaterial.MaterialID;
					}
					else
					{
						ltrMsg.Text = msg;
					}
				}
				else
				{
					if(_MaterialProvider.UpdateMaterial(theMaterial))
					{
						if(!chbIsPublic.Checked)
						{
							List<int> lstSelectedDrugStoreIDs = new List<int>();
							foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
							{
								if(item.Selected)
								{
									lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
								}
							}

							List<RLT_MaterialAndShareTo> lstMaterialAndShareTo = new List<RLT_MaterialAndShareTo>();

							if(lstSelectedDrugStoreIDs.Count > 0)
							{
								foreach(var id in lstSelectedDrugStoreIDs)
								{
									var rltMaterialAndShareTo = new RLT_MaterialAndShareTo() { MaterialID = theMaterial.MaterialID, ShareToDrugStoreID = id };
									lstMaterialAndShareTo.Add(rltMaterialAndShareTo);
								}
							}

							if(lstMemberSelected.Items.Count > 0)
							{
								foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
								{
									var memberID = int.Parse(item.Value);
									var rltMaterialAndShareTo = new RLT_MaterialAndShareTo() { MaterialID = theMaterial.MaterialID, ShareToMemberID = memberID };
									lstMaterialAndShareTo.Add(rltMaterialAndShareTo);
								}
							}

							_MaterialProvider.SaveMaterialAndShareTo(theMaterial.MaterialID, lstMaterialAndShareTo);
						}

						ltrMsg.Text = "保存成功";
					}
					else
					{
						ltrMsg.Text = "保存失败";
					}
				}
			}
		}

		private void BindMaterialCategory()
		{
			if(_MaterialProvider == null)
			{
				_MaterialProvider = new MaterialProvider();
			}

			ddlMaterialCategory.Items.Clear();
			ddlMaterialCategory.DataSource = _MaterialProvider.GetAllMaterialCategory();
			ddlMaterialCategory.DataBind();
		}

		private void BindDrugStore()
		{
			chblstDrugStore.Items.Clear();
			chblstDrugStore.DataSource = GetDrugStore();
			chblstDrugStore.DataBind();

			ddlDrugStore.Items.Clear();
			ddlDrugStore.DataSource = GetDrugStore();
			ddlDrugStore.DataBind();

			BindMember();
		}

		private void BindMember()
		{
			if(!string.IsNullOrWhiteSpace(ddlDrugStore.SelectedValue))
			{
				var selectedDrugStoreID = int.Parse(ddlDrugStore.SelectedValue);

				var userProvider = new UserProvider();

				lstMember.DataSource = userProvider.GetUserByDrugStore(selectedDrugStoreID, true);
				lstMember.DataBind();
			}
		}

		private List<DrugStore> GetDrugStore()
		{
			List<DrugStore> result;

			if(this.lstDrugStore != null)
			{
				result = lstDrugStore;
			}
			else
			{
				var drugStoreProvider = new DrugStoreProvider();

				lstDrugStore = drugStoreProvider.GetAllDrugStore();

				result = lstDrugStore;
			}

			return result;
		}

		private void BindMaterial()
		{
			if(MaterialID > 0)
			{
				if(_MaterialProvider == null)
				{
					_MaterialProvider = new MaterialProvider();
				}

				var theMaterial = _MaterialProvider.GetMaterial(MaterialID);

				if(theMaterial != null)
				{
					this.txtMaterialName.Text = theMaterial.MaterialName;
					this.txtMaterialDescription.Text = theMaterial.MaterialDescription;
					this.txtMaterialReqiredScore.Text = theMaterial.DownloadRequiedScore.GetValueOrDefault(0).ToString();

					if(ddlMaterialCategory.Items.Count > 0)
					{
						foreach(ListItem item in ddlMaterialCategory.Items)
						{
							if(item.Value.Equals(theMaterial.MaterialCategoryID.GetValueOrDefault(0).ToString()))
							{
								item.Selected = true;
							}
						}
					}

					if(theMaterial.IsPublic != 1)
					{
						var materialAndShareTo = _MaterialProvider.GetMaterialAndShareToByMaterial(theMaterial.MaterialID);

						if(materialAndShareTo != null && materialAndShareTo.Count > 0)
						{
							var materialAndShareToDrugStore = materialAndShareTo.Where(vs => vs.ShareToDrugStoreID > 0);
							var materialAndShareToMember = materialAndShareTo.Where(vs => vs.ShareToMemberID > 0);

							if(materialAndShareToDrugStore != null)
							{
								var lstMaterialShareToDrugStore = materialAndShareToDrugStore.ToList();

								if(lstMaterialShareToDrugStore.Count > 0)
								{
									foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
									{
										var drugStoreID = int.Parse(item.Value);

										item.Selected = lstMaterialShareToDrugStore.Count(vs => vs.ShareToDrugStoreID == drugStoreID) > 0;
									}
								}
							}

							lstMemberSelected.Items.Clear();

							if(materialAndShareToMember != null)
							{
								var lstMaterialShareToMember = materialAndShareToMember.ToList();

								if(lstMaterialShareToMember.Count > 0)
								{
									var data = from vs in lstMaterialShareToMember
														 select new { UserCName = vs.User.UserCName, ShareToMemberID = vs.ShareToMemberID };

									foreach(var dataItem in data)
									{
										var item = new System.Web.UI.WebControls.ListItem(dataItem.UserCName, dataItem.ShareToMemberID.ToString());

										//if (!lstMemberSelected.Items.Contains(item))
										//{
										lstMemberSelected.Items.Add(item);
										//}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}